package com.company.tree;

public class DictionaryOfWord {

    private final DictionaryTreeNode root = new DictionaryTreeNode("");

    public void insertNewWord(String word){
        if (word == null || word.equals("")) {
            return;
        }
        DictionaryTreeNode currentNode = root;
        for (int i = 0; i < word.length(); i++) {
            String c = word.substring(i,i+1);
            boolean hasNode=false;
            for (DictionaryTreeNode mChild : currentNode.mChildren) {
                if (mChild.val.equals(c)) {
                    //如果同说明可以继续向下
                    hasNode = true;
                    currentNode = mChild;
                    break;
                }
            }

            if (hasNode) {
                continue;
            }
            //如果没有 增加节点
            DictionaryTreeNode newNode = new DictionaryTreeNode(c);
            currentNode.mChildren.add(newNode);
            currentNode = newNode;
        }
        currentNode.endFlag = true;
    }

    public boolean hasWord(String word) {
        if (word == null || word.equals("")) {
            return false;
        }
        DictionaryTreeNode currentNode = root;
        for (int i = 0; i < word.length(); i++) {
            String c = word.substring(i,i+1);
            boolean hasNode=false;
            for (DictionaryTreeNode mChild : currentNode.mChildren) {
                if (mChild.val.equals(c)||c.equals(".")) {
                    //如果同说明可以继续向下
                    hasNode = true;
                    currentNode = mChild;
                    break;
                }
            }

            if (hasNode) {
                continue;
            }
            return false;
        }

        return currentNode.endFlag;
    }
}
